package com.zhoutao123.hephaestus.config;

import com.zhoutao123.hephaestus.object.exception.BaseException;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import lombok.Data;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;

@ControllerAdvice
@Slf4j
public class ExceptionHandle {
    @ExceptionHandler(value = BaseException.class)
    @ResponseBody
    public ResponseEntity<ErrorResponse> processWebApplicationException(BaseException e) {
        return new ResponseEntity<>(new ErrorResponse(e), e.getStatus());
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseEntity<ErrorResponse> processGeneralException(Exception e) {
        log.error("Escaped exception", e);
        return new ResponseEntity<>(new ErrorResponse(e), HttpStatus.BAD_REQUEST);
    }

    @Accessors(chain = true)
    @Data
    static class ErrorResponse {
        String message;

        ErrorResponse(String message) {
            this.message = message;
        }

        ErrorResponse(Throwable e) {
            this.message = e.getMessage();
        }
    }
}
